<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="合同编号" prop="contractNo">
        <el-select
          v-model="queryParams.contractNo"
          placeholder="合同编号"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in contractList"
            :key="item.id"
            :label="item.contractNo"
            :value="item.contractNo"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户手机号" prop="customerMobile">
        <el-input
          v-model="queryParams.customerMobile"
          placeholder="请输入客户手机号"
          clearable
          style="width: 200px"
          maxlength="11"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 客户类别 -->
      <el-form-item label="客户类别" prop="customerType">
        <el-select
          v-model="queryParams.customerType"
          placeholder="请选择"
          clearable
          style="width: 200px"
        >
          <el-option label="卖方" value="1"></el-option>
          <el-option label="买方" value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="客户姓名" align="center" prop="customerName" />
      <el-table-column label="客户手机号" align="center" prop="customerPhone" />
      <el-table-column label="客户类别" align="center" prop="customerType">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.customerType == 1"
            >卖方</el-tag
          >
          <el-tag type="danger" v-else>买方</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="房屋地址" align="center" prop="houseAddress" />
      <el-table-column
        label="成本类别"
        align="center"
        prop="costTypeItemsStr"
      />
      <el-table-column label="成本费用" align="center" prop="countTotalPrice">
        <template #default="scope">
          <span>{{
            scope.row.countTotalPrice ? `${scope.row.countTotalPrice}元` : `0元`
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNo">
              <el-select
                v-model="form.contractNo"
                placeholder="合同编号"
                filterable
                @change="handleContractNoChange"
                style="width: 200px"
                :disabled="form.id"
              >
                <el-option
                  v-for="item in contractList"
                  :key="item.id"
                  :label="item.contractNo"
                  :value="item.contractNo"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户类型" prop="customerType">
              <el-radio-group
                v-model="form.customerType"
                @change="handleCustomerTypeChange"
                :disabled="form.id"
              >
                <!-- 买方 -->
                <el-radio :value="2">买方</el-radio>
                <!-- 卖方 -->
                <el-radio :value="1">卖方</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input
                v-model="form.customerName"
                readonly
                placeholder="请输入客户姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户手机号" prop="customerPhone">
              <el-input
                v-model="form.customerPhone"
                readonly
                maxlength="11"
                placeholder="请输入客户手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 房屋地址 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="房屋地址" prop="houseAddress">
              <el-input
                v-model="form.houseAddress"
                readonly
                placeholder="请输入房屋地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <!-- 成本类别 -->
            <el-form-item label="成本类别" prop="costTypeItems">
              <el-select
                v-model="form.costTypeItems"
                multiple
                placeholder="请选择成本类别"
                @change="handleCostTypeChange"
              >
                <el-option
                  v-for="item in costTypeItemList"
                  :key="item.id"
                  :label="item.costName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="10"
          v-for="item in form.costItems"
          :key="item.costingId"
        >
          <el-col :span="8">
            <el-form-item label=" ">
              <el-input v-model="item.costName" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="auto">
              <el-input
                v-model="item.costingPrice"
                placeholder="原始金额"
                @blur="handleCostingPriceBlur(item)"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="auto">
              <el-input
                placeholder="计算金额"
                v-model="item.countCostingPrice"
                readonly
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CostManager">
import {
  listCost,
  listContract,
  listNotice,
  costTypeList,
  addCost,
  getCost,
  editCost,
  delCost,
  queryCostingPrice,
} from "@/api/business/costManager";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const route = useRoute();
const contractNo = route.query.contractNo;

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    contractNo: [
      { required: true, message: "请选择合同编号", trigger: "change" },
    ],
    customerType: [
      { required: true, message: "请选择客户类型", trigger: "change" },
    ],
    customerName: [
      { required: true, message: "请输入客户姓名", trigger: "blur" },
    ],
    customerPhone: [
      { required: true, message: "请输入客户手机号", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号",
        trigger: "blur",
      },
    ],
    houseAddress: [
      { required: true, message: "请输入房屋地址", trigger: "blur" },
    ],
    paymentItem: [
      { required: true, message: "请选择缴费项目", trigger: "change" },
    ],
    paymentAmount: [
      { required: true, message: "请输入付费金额", trigger: "blur" },
    ],
    paymentStatus: [
      { required: true, message: "请选择付款状态", trigger: "change" },
    ],
    feeCharge: [{ required: true, message: "请输入手续费", trigger: "blur" }],
    costTypeItems: [
      { required: true, message: "请选择成本类别", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
queryParams.value.contractNo = contractNo;
console.log(queryParams.value);
//成本类别列表
const costTypeItemList = ref([]);
function getCostTypeList() {
  costTypeList().then((response) => {
    costTypeItemList.value = response.data;
  });
}
getCostTypeList();

/** 查询岗位列表 */
function getList() {
  loading.value = true;
  listCost(queryParams.value).then((response) => {
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
//监听成本价输入
function handleCostingPriceBlur(item) {
  if (item.costingPrice == "") {
    item.countCostingPrice = "";
    return;
  }
  const data = {
    costingId: item.costingId,
    costingPrice: item.costingPrice,
  };
  queryCostingPrice(data).then((response) => {
    item.countCostingPrice = response.data;
  });
}
//获取合同列表
const contractList = ref([]);
function getContractList() {
  listContract().then((response) => {
    contractList.value = response.data;
  });
}
getContractList();

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

//监听成本类别选择
function handleCostTypeChange(value) {
  // 将现有数据转换为 Map，以 costingId 为 key
  const existingDataMap = new Map();
  form.value.costItems.forEach((item) => {
    existingDataMap.set(item.costingId, item);
  });

  // 根据新选择的值重新构建数组
  form.value.costItems = value.map((id) => {
    const existingItem = existingDataMap.get(id);
    const costTypeItem = costTypeItemList.value.find((v) => v.id === id);

    if (existingItem) {
      // 保留现有数据
      return existingItem;
    } else {
      // 新增项目
      return {
        costingId: id,
        costName: costTypeItem.costName,
        costingPrice: "",
        countCostingPrice: "",
      };
    }
  });
}
//监听合同编号选择
function handleContractNoChange(value) {
  reset();
  form.value.contractNo = value;
}
//监听买方卖方
function handleCustomerTypeChange(value) {
  if (!form.value.contractNo) {
    proxy.$modal.msgError("请先选择合同编号");
    return;
  }
  const data = {
    contractNo: form.value.contractNo,
    customerType: value,
  };

  listNotice(data).then((response) => {
    const { noticeOrderItemList, ...reset } = response.data;
    form.value = {
      ...form.value,
      ...reset,
    };
  });
}
/** 表单重置 */
function reset() {
  form.value = {
    costItems: [],
  };
  proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  if (contractNo) {
    form.value.contractNo = contractNo;
  } else {
    form.value.contractNo = queryParams.value.contractNo;
  }
  open.value = true;
  title.value = "添加";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id;
  getCost(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改";
    handleCustomerTypeChange(form.value.customerType);
  });
}
//验证成本类别下的各个项是否有值
function validateCostingPrice() {
  const valid = form.value.costItems.every((v) => v.costingPrice);
  if (!valid) {
    proxy.$modal.alertError("请输入成本价");
    return false;
  }
  return true;
}
/** 提交按钮 */
function submitForm() {
  if (!validateCostingPrice()) {
    return;
  }

  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        editCost(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCost(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(function () {
      return delCost(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/post/export",
    {
      ...queryParams.value,
    },
    `post_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
